import logging

import pytest

from resource.pom.settings import Settings
from resource.pom.system_ui import SystemUI
from utils.manager import Direction, Images, MatchRules
from utils.device import Device


class Test:
    app = Settings
    system_ui = SystemUI

    @pytest.mark.parametrize('setup_teardown', [app.bundle_name], indirect=True)
    def test(self, setup_teardown, device):
        logging.info('步骤1.进入桌面，点击设置-蓝牙，开启设备A的蓝牙按钮')
        device.start_ability(self.app.bundle_name, self.app.ability_name)
        device.wait(1)
        device.dirc_fling(Direction.Up)
        device.click(*self.app.bluetooth_item)
        device.refresh_layout()
        # 检查wifi开关状态
        toggle = device.get_element_by_type('Toggle')
        if toggle.get('checked') == 'false':
            device.click_element(toggle)
        device.wait(10)
        logging.info('预期结果1.蓝牙按钮被点亮，并在通知栏显示蓝牙的图标，附近可配对的蓝牙显示在可用设备列表中')
        status_bar = device.save_snapshot_to_local('statusbar.jpeg')
        Images.crop_picture(status_bar, *self.system_ui.statusbar_area)
        assert Images.is_image_in_image(self.system_ui.bluetooth_icon, status_bar), '状态栏没有蓝牙图标'

        device.assert_text_exist('可用设备')
        bluetooth = self.app.bluetooth()
        device.assert_text_exist(bluetooth['name'])

        logging.info('步骤2.可用设备列表选择设备B，点击配对进行连接')
        deviceB = Device(bluetooth['sn'])
        self.app.open_bluetooth_switch(deviceB)
        device.refresh_layout()
        device.click_element(device.get_element_by_text(bluetooth['name']))
        device.refresh_layout()

        logging.info('预期结果2.设备A显示配对请求，设备B显示配对请求，同时点击设备A和B的配对按钮，蓝牙配对成功')
        device.assert_text_exist('蓝牙配对请求')
        device.assert_text_exist('要与您配对。请确认此配对码', MatchRules.Contain)
        device.assert_type_exist('Checkbox')
        device.assert_text_exist('配对之后，向所配对设备授予通讯录和通话记录的访问权限。')
        associateA = device.get_element_by_text('配对')
        win_name, win_id = device.get_focus_window()
        text_elements = device.get_elements_by_condition(condition={"hostWindowId": win_id})
        code = ''
        for e in text_elements:
            if e.get('text').isdigit():
                code = e.get('text')
                break
        assert code, '配对码为空'

        deviceB.refresh_layout()
        deviceB.assert_text_exist('蓝牙配对请求')
        deviceB.assert_text_exist('要与您配对。请确认此配对码', MatchRules.Contain)
        deviceB.assert_type_exist('Checkbox')
        deviceB.assert_text_exist('配对之后，向所配对设备授予通讯录和通话记录的访问权限。')
        deviceB.assert_text_exist(code)
        deviceB.click_element(deviceB.get_element_by_text('配对'))

        device.click_element(associateA)
        device.refresh_layout()
        device.assert_text_exist('已配对的设备')
        device.assert_text_exist(bluetooth['name'])